$(function(){
    bky = {};
    bky.pageIndex = 1;
    bky.iframeTag = 'nwdisable nwfaketop nwUserAgent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.6.12501.400"';
    bky.articleDiv = '<iframe id="articleFrame" src="https://i.cnblogs.com/EditPosts.aspx?opt=1" '+bky.iframeTag+'></iframe>';
    bky.loginFlag = false;
    bky.imgUploadUrl = "https://upload.cnblogs.com/imageuploader/CorsUpload";
    bky.version = 500000001;
    bky.checkUpdate = function(){
        $.get("http://www.cnblogs.com/liulun/articles/7710391.html",function(r){
            var trueVersion = $(r).find("#51cnblogsVersion").html();
            trueVersion = parseInt($.trim(trueVersion));
            if(bky.version < trueVersion){
                alert("有新版本，您需要升级");
                nw.Shell.openExternal('https://gitee.com/xland/cnblogs/releases');
            }
        })
    }
    bky.editArticleHandler = function(){
        //https://i.cnblogs.com/PostDone.aspx?postid=7681073&actiontip=%e4%bf%9d%e5%ad%98%e4%bf%ae%e6%94%b9%e6%88%90%e5%8a%9f
        var frame = document.getElementById('articleFrame').contentWindow;
        if(frame.location.href.search('signin')>-1){ //需要登录
            $("#articleListBg").hide();
            bky.loginFlag = true;
            $("#articleFrame").show();
            frame.$("a").attr("href","javascript:alert('该工具不能完成此特殊操作，请去博客园网页版操作');")
            return;
        }
        if(bky.loginFlag && frame.location.href.search('EditPosts.aspx')>-1){ //刚刚登录成功
            $("#articleFrame").hide();
            bky.loginFlag = false;
            return
        }
        var msg = frame.location.href.split('=');
        msg = msg[msg.length -1];
        msg = decodeURI(msg);
        if(msg == "保存修改成功" || msg == '发布成功' || msg == '保存草稿成功' || msg == '存为草稿成功'){ //保存文章成功
            alert("保存成功");
            var url = 'https://i.cnblogs.com/'+frame.$("#TipsPanel_LinkEdit").attr("href");
            frame.location.href = url;
            return;
        }
        setTimeout(function(){
            frame.onbeforeunload = undefined;
            var title = frame.$("#Editor_Edit_txbTitle").val();
            var content = frame.$('#Editor_Edit_EditorBody').val();
            content = $(content).html();
            $("#titleInput").val(title);
            editorFrame.body.innerHTML = content?content:"";
            $("#articleListBg").hide();
            iframeBodyReady();
        },600);
    }
    bky.editArticle = function(){
        $("#articleListWrapper").hide();
        var id = $(this).attr("id");
        $("#articleFrame").attr("src",'https://i.cnblogs.com/EditPosts.aspx?postid='+id);
    }
    bky.newArticle = function(){
        if($("#titleInput").val().length > 0){
            var flag = confirm("您现在处于编辑文章的状态，确实要退出吗？");
            if(!flag){
                return;
            }        
        }
        $("#articleListBg").show();
        $("#articleListWrapper").hide();
        $("#articleFrame").attr("src",'https://i.cnblogs.com/EditPosts.aspx?opt=1');
    }
    
    bky.saveArticle = function(obj){ 
        $("#articleListBg").show();
        $("#articleListWrapper").hide();
        var frame = document.getElementById('articleFrame').contentWindow;
        frame.$("#Editor_Edit_txbTitle").val(obj.title);
        frame.blogEditor.setContent(obj.content);
        var btn = frame.$("#Editor_Edit_lkbDraft");
        if(btn.length > 0){ //能存草稿就存草稿
            btn.click();
            return;
        }
        frame.$("#Editor_Edit_lkbPost").click();
    }
    bky.uploadImg = function(file,cb){
        $("#articleListBg").show();        
        var formData = new FormData();
        formData.append('imageFile', file);
        formData.append("mimeType", file.type);
        var frame = document.getElementById('articleFrame').contentWindow
        frame.$.ajax({
            type: 'POST',
            url:bky.imgUploadUrl,
            data: formData,
            processData: false, 
            contentType: false, 
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: function(result) {
                $("#articleListBg").hide();
                if(result.success){
                    cb(result.message);
                }
            }
        });    
    }
    
    bky.getList = function(pageIndex){
        $.get("https://i.cnblogs.com/posts?page="+pageIndex,function(r){
            $("#articleListBg").show();
            var doc = $(r);
            if(!doc.find("#TabPosts")){
                bky.showLogin();
                return;
            }
            var lastPager = doc.find(".pager .current").html();
            if(parseInt(lastPager)<pageIndex){
                return;
            }
            $(".titleRow").remove();        
            doc.find(".post-title a").each(function(index,item){
                var id = $(item).attr("href").split('/');
                id = id[id.length-1]
                id = id.split('.')[0];
                var indexNum = index+1+(pageIndex-1)*30;
                var str = $(item).html();
                str = '<div class="titleRow" id="'+id+'">'+indexNum+':&nbsp;'+str+'</div>';
                if(index < 15){
                    $("#articleLeft").append(str);
                }else{
                    $("#articleRight").append(str);
                }            
            })
            $(".titleRow").click(bky.editArticle);
            bky.pageIndex = pageIndex;
            $("#articleListWrapper").show();
        })
    }
    bky.init = function(){        
        bky.checkUpdate();
        $("body").append(bky.articleDiv);
        $("#articleListBg").show();
        $("#articleFrame").on("load",bky.editArticleHandler);
    }
    //bky.init();
})